package com.touchsun.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 统一跨域请求配置
 *
 * @author lee
 * @since 2023/2/26 22:15
 */
@Configuration
public class CorsConfig {

    /**
     * 跨域方法配置
     * 
     * @return 跨域配置对象
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 配置对象[使用URL配置]
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        // 跨域配置 *表示所有
        CorsConfiguration config = new CorsConfiguration();
        
        // - 允许跨域的HTTP请求方法类型
        config.addAllowedMethod("*");
        // - 允许跨域的请求头
        config.addAllowedHeader("*");
        // - 允许跨域的源
        config.addAllowedOriginPattern("*");
        // - 允许携带Cookie跨域
        config.setAllowCredentials(true);
        
        // 配置路径规则[/**:所有路径]
        configSource.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(configSource);
    }
}
